//
//  RMMChooseSkillViewController.m
//  Romomo
//
//  Created by puman on 16/10/17.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMChooseSkillViewController.h"
#import "RMMChooseSkillTableViewCell.h"
#import "RMMAdressTableViewCell.h"
#import "RMMOderAdressViewController.h"
#import "RMMUpOrderViewController.h"
#import "RMMChooseFuWuViewController.h"
#import "RMMSkillDeltailsViewController.h"

@interface RMMChooseSkillViewController ()<UITableViewDelegate, UITableViewDataSource>

@end

@implementation RMMChooseSkillViewController
{
    UITableView *_tableView;
    RMMNotNetWorkView *_networkView;
    UIButton *_bottomBut;
    NSMutableDictionary *_dataDic;
    NSString *_skill_id;
    NSString *_skill_name;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    self.navigationItem.title = @"选择我的技师";
    [self addViews];
    [self getRequestData];
    // Do any additional setup after loading the view.
}
- (void)addViews{
    _dataDic = [NSMutableDictionary dictionary];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64 - 49) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[RMMChooseSkillTableViewCell class] forCellReuseIdentifier:@"MyCell"];
    [_tableView registerClass:[RMMAdressTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:_tableView];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
    [self addBottomViews];
    _networkView = [[RMMNotNetWorkView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _networkView.hidden = YES;
    BUTTON_S(_networkView.button, networkBut);
    [self.view addSubview:_networkView];
}
- (void)networkBut{
    [self getRequestData];
}
- (void)addBottomViews{
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 49 - 64, kScreenWideth, 49)];
    bottomView.backgroundColor = kWhiteColor;
    [self.view addSubview:bottomView];
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, bottomView.width, 0.5)];
    lineLabel.backgroundColor = RGBA(221, 221, 221, 1);
    [bottomView addSubview:lineLabel];
    
    _bottomBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _bottomBut.frame = CGRectMake(kScreenWideth / 2 - kHalf * 2, 6.5, 4 * kHalf, 36);
    _bottomBut.backgroundColor = RGBA(237, 238, 239, 1);
    [_bottomBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
    _bottomBut.titleLabel.font = kBFont(14);
    _bottomBut.layer.masksToBounds = YES;
    _bottomBut.layer.cornerRadius = 18;
    [_bottomBut setTitle:@"下一步" forState:(UIControlStateNormal)];
    _bottomBut.userInteractionEnabled = NO;
    BUTTON_S(_bottomBut, nextButClick);
    [bottomView addSubview:_bottomBut];
}
- (void)getRequestData{
    NSDictionary *dic = [[RMMFileManager shareHandle].bookingDic objectForKey:@"地址"];
    id adress_id = [dic objectForKey:@"ID"];
    NSString *bookingTime = [[RMMFileManager shareHandle].bookingDic objectForKey:@"时间"];
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"regin_id"] = [RMMFileManager shareHandle].region_id;
    parDic[@"service_type"] = _isHome;
    if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        parDic[@"res_type"] = @"3";

    } else {
        parDic[@"res_type"] = @"2";
    }
    if ([_isHome isEqualToString:@"1"]) {
        parDic[@"store_id"] = @"-10";
        parDic[@"address_id"] = adress_id;
    } else {
        parDic[@"store_id"] = adress_id;
        parDic[@"address_id"] = @"-1";
    }
    parDic[@"emp_id"] = @"-1";
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *time = [dateFormatter stringFromDate:date];
    parDic[@"query_time"] = bookingTime == nil ? time : bookingTime;
    parDic[@"time_len"] = [RMMFileManager shareHandle].totalTimeLength;
    NSString *url = GetTimeOrSkillUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic network:^(BOOL isNetwork) {
        if (isNetwork) {
            _networkView.hidden = YES;
        } else {
            _networkView.hidden = NO;
        }
    } method:POST finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NSArray *array = dataDic[@"data"];
            NSMutableArray *value = _dataDic[@"附近技师"];
            if (value == nil) {
                value = [NSMutableArray array];
                [_dataDic setObject:value forKey:@"附近技师"];
            }
            NSMutableArray *arrayM = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                RMMSkillModel *model = [[RMMSkillModel alloc] init];
                [model setValuesForKeysWithDictionary:[RMMFileManager setValueForDic:dic[@"EMPDETAIL"]][@"EMP_IMAGE"]];
                model.Is_Avaliable = dic[@"Is_Avaliable"];
                model.SVA_SCORE = [RMMFileManager setValueForDic:dic[@"EMPDETAIL"]][@"SVA_SCORE"];
                model.type = @"0";
                if ([model.Is_Avaliable isEqualToNumber:@1]) {
                    [value addObject:model];
                } else {
                    [arrayM addObject:model];
                }
            }
            for (RMMSkillModel *model in arrayM) {
                [value addObject:model];
            }
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];

    } error:^(NSError *errors) {
        
    } view:self.view];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        return 1 + [_dataDic allKeys].count;
    } else {
        return [_dataDic allKeys].count;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        if (section == 0) {
            return 1;
        } else {
            NSArray *array = [_dataDic allKeys];
            NSString *key = array[section - 1];
            NSMutableArray *value = _dataDic[key];
            return value.count;
        }
    } else {
        NSArray *array = [_dataDic allKeys];
        NSString *key = array[section];
        NSMutableArray *value = _dataDic[key];
        return value.count;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        if (section == 1) {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 40)];
            view.backgroundColor = RGBA(243, 246, 247, 1);
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kScreenWideth - 30, 40)];
            label.font = kFont(14);
            label.textColor = COLORFROMCODE(0x9B9B9B, 1);
            NSArray *array = [_dataDic allKeys];
            label.text = array[section - 1];
            [view addSubview:label];
            return view;
        } else {
            return nil;
        }
    } else {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 40)];
        view.backgroundColor = RGBA(243, 246, 247, 1);
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, kScreenWideth - 30, 40)];
        label.font = kFont(14);
        label.textColor = COLORFROMCODE(0x9B9B9B, 1);
        NSArray *array = [_dataDic allKeys];
        label.text = array[section];
        [view addSubview:label];
        return view;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        if (section == 1) {
            return 40;
        } else {
            return 0;
        }
    } else {
        return 40;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 90;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        if (indexPath.section == 0) {
            RMMAdressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            NSDictionary *dic = [[RMMFileManager shareHandle].bookingDic objectForKey:@"地址"];
            cell.titleLabel.text = @"地址已选";
            cell.number = @2;
            cell.dic = [RMMFileManager setValueForDic:dic];
            return cell;
        } else {
            RMMChooseSkillTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            NSArray *array = [_dataDic allKeys];
            NSString *key = array[0];
            NSMutableArray *value = _dataDic[key];
            RMMSkillModel *model = value[indexPath.row];
            cell.model = model;
            cell.selcetBut.tag = indexPath.row + 1;
            BUTTON_S(cell.selcetBut, selcetButClick:);
            return cell;
        }
    } else {
        RMMChooseSkillTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSArray *array = [_dataDic allKeys];
        NSString *key = array[0];
        NSMutableArray *value = _dataDic[key];
        RMMSkillModel *model = value[indexPath.row];
        cell.model = model;
        cell.selcetBut.tag = indexPath.row + 1;
        BUTTON_S(cell.selcetBut, selcetButClick:);
        return cell;
    }
}
- (void)selcetButClick:(UIButton *)button{
    NSArray *array = [_dataDic allKeys];
    NSString *key = array[0];
    NSMutableArray *value = _dataDic[key];
    RMMSkillModel *model = value[button.tag - 1];
    if ([model.Is_Avaliable isEqualToNumber:@1]) {
        for (int i = 0; i < value.count; i++) {
            RMMSkillModel *models = value[i];
            if ( i + 1 == button.tag) {
                if ([models.type isEqualToString:@"1"]) {
                    models.type = @"0";
                    _skill_name = @"";
                    _skill_id = @"";
                } else {
                    models.type = @"1";
                    _skill_name = models.EMP_NAME;
                    _skill_id = models.EMP_ID;
                }
            } else {
                models.type = @"0";
            }
        }
    }
    [_tableView reloadData];
    if (_skill_id.length) {
        _bottomBut.userInteractionEnabled = YES;
        _bottomBut.backgroundColor = kBasicColor;
        [_bottomBut setTitleColor:kWhiteColor forState:(UIControlStateNormal)];
    } else {
        _bottomBut.backgroundColor = RGBA(237, 238, 239, 1);
        [_bottomBut setTitleColor:RGBA(212, 213, 214, 1) forState:(UIControlStateNormal)];
        _bottomBut.userInteractionEnabled = NO;
    }

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array = [_dataDic allKeys];
    NSString *key = array[0];
    NSMutableArray *value = _dataDic[key];
    RMMSkillModel *model = value[indexPath.row];
    RMMSkillDeltailsViewController *VC = [[RMMSkillDeltailsViewController alloc] init];
    VC.emp_id = model.EMP_ID;
    VC.type = @"1";
    [self.navigationController pushViewController:VC animated:YES];
}
- (void)nextButClick{
    NSDictionary *dic = @{@"EMP_NAME":_skill_name,@"EMP_ID":_skill_id};
    [[RMMFileManager shareHandle].bookingDic setValue:dic forKey:@"技师"];
    if ([[RMMFileManager shareHandle].fromSkillType isEqualToString:@"1"]) {
        RMMChooseFuWuViewController *VC = [[RMMChooseFuWuViewController alloc] init];
        NSDictionary *dic = @{@"EMP_NAME":_skill_name,@"EMP_ID":_skill_id};
        [[RMMFileManager shareHandle].bookingDic setValue:dic forKey:@"技师"];
        VC.isHome = _isHome;
        [self.navigationController pushViewController:VC animated:YES];
    } else {
        if ([_type isEqualToString:@"2"]) {
            NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
            NSString *emp_id = [RMMFileManager retrunObjWith:[[RMMFileManager shareHandle].bookingDic objectForKey:@"技师"][@"EMP_ID"]];
            NSDictionary *dic = [RMMFileManager shareHandle].bookingDic;
            NSString *order_id = [[RMMFileManager shareHandle].bookingDic objectForKey:@"订单ID"];
            NSString *bookingTime = [[RMMFileManager shareHandle].bookingDic objectForKey:@"时间"];
            parDic[@"order_id"] = order_id;
            parDic[@"time_len"] = [RMMFileManager shareHandle].totalTimeLength;
            parDic[@"emp_id"] = emp_id;
            parDic[@"begin_time"] = bookingTime;
            NSString *url = XiuGaiOrderUrl;
            [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
                NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
                if ([status isEqualToString:@"1"]) {
                    [MMProgressHUD show];
                    [MMProgressHUD dismissWithSuccess:@"订单修改成功!" title:nil afterDelay:1.0];
                    NS_POST(@"ORDERUPDATA", nil, nil);
                    NS_POST(@"OREDERDETAILS", nil, nil);
                    [[RMMFileManager shareHandle].bookingDic removeAllObjects];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    });
                } else {
                    [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
                }
            } error:^(NSError *errors) {
            } view:self.view];
            
        } else {
            NSArray *VCArray = self.navigationController.viewControllers;
            for (UIViewController *VC in VCArray) {
                if ([VC isKindOfClass:[RMMUpOrderViewController class]]) {
                    NSDictionary *dic = @{@"EMP_NAME":_skill_name,@"EMP_ID":_skill_id};
                    [[RMMFileManager shareHandle].bookingDic setValue:dic forKey:@"技师"];
                    [self.navigationController popToViewController:VC animated:YES];
                }
            }
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
